<?php
/**
 * Created by PhpStorm.
 * User: cui
 * Date: 2018/12/6
 * Time: 14:04
 */
namespace app\index\controller;

use app\common\model\MemberModel;
use think\Controller;
use think\Request;

class Index extends Controller
{
    private $url_openid = 'https://api.weixin.qq.com/sns/jscode2session';//获取session、openid

    /**
     * 构造器
     * @param Request|null $request
     */
    public function __construct(Request $request = null){
        $system = db('system')->find();
        Config($system);
        parent::__construct($request);
    }

    /**
     * 获取openid
     * @return mixed
     */
    private function getOpenId(){
        $param = [
            'appid' => Config('appid'),
            'secret' => Config('appsecret'),
            'js_code' => input('post.code')?:'',
            'grant_type' => 'authorization_code'
        ];
        $res = httpget($this->url_openid, $param);
        return json_decode($res, true);
    }

    /**
     * 小程序登陆
     * @return \think\response\Json
     */
    public function wxLogin(){
        $res = $this->getOpenId();
        if (isset($res['openid'])){
            $member = MemberModel::get(['openid'=>$res['openid']])?:new MemberModel();
            $data = input('post.');
            $data['openid'] = $res['openid'];
            $data['session_key'] = $res['session_key'];
            $data['token'] = md5(uniqid(microtime(true),true));
            $data['last_login_time'] = date('Y-m-d H:i:s');
            $data['last_login_ip'] = $_SERVER['REMOTE_ADDR'];
            $data['create_time'] = date('Y-m-d H:i:s');

            $record = $member->allowField(true)->save($data);
            if ($record){
                return json(msg(0, $member, '登陆成功！'));
            }else{
                return json(['code'=>1, 'msg'=>'登陆失败!']);
            }
        }else{
            return json(['code'=>$res['errcode'], 'msg'=>$res['errmsg']]);
        }
    }

    /**
     * 获取会员信息
     * @return \think\response\Json
     */
    public function getUserInfo(){
        $res = $this->getOpenId();
        if (isset($res['openid'])){
            $member = MemberModel::get(['openid'=>$res['openid']]);
            $member->save(['token'=>md5(uniqid(microtime(true),true))]);
            if ($member){
                return json(msg(0, $member, '登陆成功！'));
            }else{
                return json(['code'=>111, 'msg'=>'重新登陆!']);
            }
        }else{
            return json(['code'=>111, 'msg'=>$res['errmsg'].'【'.$res['errcode'].'】']);
        }
    }

    //解析会员信息
    public function login(){
        echo '2222222222222';exit;
//        $encryptedData=input('post.encryptedData');
//        $iv = input('post.iv');
//
//        //TODO 解析
//        $pc = new WXBizDataCrypt(Config('appid'), $sessionKey);
//        $errCode = $pc->decryptData($encryptedData, $iv, $data );
//
//        $data=json_decode($data,true);
    }
}